import { Tween } from 'cc';
import { _decorator, Component, Node, Label, tween, view, UITransform, Vec3, SpriteAtlas, SpriteFrame, Sprite, Button, ScrollView, find, math, RichText, EventTouch, WebView } from 'cc';
import { App } from '../App';
import { EventConst } from '../common/Common';
import CommConst from '../const/CommConst';
import wsTool from '../net/ws';
import { showErrorTip, showRewardBox } from '../tools/PopuUp';
import { TipMg } from '../tools/TipMg';
import UtilTool from '../tools/UtilTool';
import ScrollHelper from './ScrollHelper';
const { ccclass, property } = _decorator;

// 任务界面
@ccclass('TaskPanel')
export class TaskPanel extends Component {
    @property(Node)
    contentNode: Node = null;

    @property(Node)
    scrollNode: Node = null;

    @property(Node)
    emptyNode: Node = null;

    @property(SpriteFrame)
    iconFrames = [];

    private itemNum = 5
    // [listData]列表数据  [isLoading]是否加载中 [loadOver]是否加载结束(如果没有新的数据则认为是加载结束) [currPage]当前已经请求的第几页的数据 [dataDirty]是否需要重新拉取数据 
    // 记录数据
    private configData = {listData : [], isLoading : false, loadOver : false, currPage : 0, dataDirty : true, pageSize : 30}
    private recodeData = null

    onLoad() {
        UtilTool.setScreen(this.node)

    }

    start() {
        this.node.getComponent(UITransform).setContentSize(view.getVisibleSize())
        UtilTool.setSize(this.scrollNode, 3, [0, 2])
        UtilTool.setSize(this.scrollNode.getChildByName("view"), 3, [0, 2])
        UtilTool.setSize(find("view/content",this.scrollNode), 3, [0, 2])
        UtilTool.setPos(this.scrollNode, [0, 1])

        this.emptyNode.active = true

        let H = UtilTool.getGapSize().height*2
        if (H>0) {
            this.itemNum = this.itemNum + Math.ceil(H/544)
        }

        this.reqData()

    }

    /**
     * 请求数据
     */
    reqData(pInit=true) {
        this.configData.isLoading = true

        wsTool.send({"msgCode":CommConst.Req_DAILYTASK})
        .then(res =>{
            if (res?.result == 0) {
                // 数据回来
                // let res = {list:[]}
                this.recodeData= res
                this.configData.currPage = this.configData.currPage + 1
                this.configData.isLoading = false
                /* res.list = [{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e51","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e52","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0egfdhfgjfgjjfghdjdghfjghdjhygkjhuyoiuphgjdhgdjgh52000","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e53","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e54","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e55","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e56","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e57","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102}]   // 测试数据 */
                // 下面分三次加入是为了排序
                res.list.forEach(element => {
                    if (element.recordStatus==1){ // 可领取
                        this.configData.listData.push(element)
                    }
                });
                res.list.forEach(element => {
                    if (element.recordStatus==0){ // 去完成
                        this.configData.listData.push(element)
                    }
                });
                res.list.forEach(element => {
                    if (element.recordStatus==2){ // 已领取
                        this.configData.listData.push(element)
                    }
                });

                if (res.list==null || res.list.length < this.configData.pageSize) {
                    this.configData.loadOver = true
                }

                this.emptyNode.active = this.configData.listData.length<=0?true:false
                this.checkIsHaveAward()
                // 最新请求的数据列表大于0，才会去刷新界面
                if (res.list.length>0) {
                    let param = {
                        init:pInit, 
                        data:this.configData.listData, 
                        itemNum:this.itemNum, 
                        itemFun: (obj,idx,objIdx)=>{
                            this.refreshItem(obj,idx,objIdx)
                        },
                        endFun:()=>{
                            this.OnScrollEnd()
                        }
                    }
    
                    this.scrollNode.getComponent(ScrollHelper).setData(param)
                }
                 
                
            }
            else{
                alert('获取数据失败')
            } 
        })
    }

    /** 
     * 刷新数据
     * param obj item对象
     * param idx 实际的下标索引
     * param objIdx item本身的下标索引
    */
    refreshItem(obj,idx,objIdx) {
        if (this.configData.listData.length <= 0) {
            return
        }

        let nameLabel = find("bg/nameLabel", obj).getComponent(Label)       // 任务名
        let mesLabel = find("bg/mesLabel", obj).getComponent(Label)         // 任务内容
        let starLabel = find("bg/starLabel", obj).getComponent(Label)       // 任务奖励星币数

        let iconImg = find("bg/iconImg", obj).getComponent(Sprite)          // 任务icon
        let btn_claim = find("bg/btn_claim", obj)       // 领取按钮 
        let btn_goto = find("bg/btn_goto", obj)         // 去完成按钮 
        let btn_haveClaim = find("bg/btn_haveClaim", obj) // 已完成按钮 

        // 数据
        let itemData = this.configData.listData[idx]
        // 名字
        nameLabel.string = App.language.getLanguageLab(208)[itemData.type + ""] || ""
        // 描述
        mesLabel.string = App.language.getLanguageLab(209)[itemData.type + ""] || ""
        // 星币数
        starLabel.string = "+" + itemData.reward
        // icon
        iconImg.spriteFrame = this.iconFrames[itemData.type]

        // 按钮 状态 0:未完成 1:已完成 2:已领取
        btn_goto.active = itemData.recordStatus == 0
        btn_claim.active = itemData.recordStatus == 1
        btn_haveClaim.active = itemData.recordStatus == 2

        // 领取
        btn_claim.off(Node.EventType.TOUCH_END)
        btn_claim.on(Node.EventType.TOUCH_END,(event: EventTouch) =>{
            UtilTool.printLog("点击 领取")
            
            this.clickCliam(itemData.recordId, itemData.reward, ()=>{
                itemData.recordStatus = 2
                btn_claim.active = itemData.recordStatus == 1
                btn_haveClaim.active = itemData.recordStatus == 2
                this.checkIsHaveAward()
            })
        },btn_claim)

        // 去完成
        btn_goto.off(Node.EventType.TOUCH_END)
        btn_goto.on(Node.EventType.TOUCH_END,(event: EventTouch) =>{
            UtilTool.printLog("点击 去完成")
            
            this.clickGoto(itemData.type)
        },btn_goto)
        
    }

    // 滚动视图滑到底部回调
    OnScrollEnd() {
        if (this.configData.isLoading) {
            return
        }
        if (this.configData.loadOver) {
            return
        }

        this.reqData(false)
    }

    /**检测是否有可领取的奖励 */
    checkIsHaveAward(){
        let count = 0
        this.configData.listData.forEach(element => {
            if (element.recordStatus == 1) {
                count = count + 1
            }
        });

        App.Event.emit(EventConst.UPDATE_TASK_HD, count)

        return count
    }

    /**请求领取奖励 */
    clickCliam(recordId, reward, cb) {
        App.Audio.playOneShot("click")
        let reward2 = reward
        wsTool.send({"msgCode":CommConst.Req_DAILYTASK_CLAIM, "recordId":recordId})
        .then(res =>{
            if (res?.result == 0) {
                showRewardBox(1, reward2)
                cb && cb()
            }
            else{
                showErrorTip(res.result)
            } 
        })
    }

    /**去完成 type: [0]每日登录 [1]幸运台球 [2]血流成河 [3]四球开伦 [4]多人台球 */ 
    clickGoto(type) {
        App.Audio.playOneShot("click")
        if (App.hallPanel) {
            App.hallPanel.clickJumpPanel(type)
        }
        this.node.destroy();
    }

    /** 
     * 关闭
      */
    clickClose() {
        App.Audio.playOneShot("click")
        this.node.destroy();
    }
    
}

